/**
 * Copyright 2007-2008. Chongqing First Information & Network Co., Ltd. All
 * rights reserved. <a>http://www.cqfirst.com.cn</a>
 */
package com.cqcis.uip.base.framework.core.impl;

import java.util.Iterator;

import com.cqcis.uip.base.framework.common.impl.AttributesImpl;
import com.cqcis.uip.base.framework.core.Endpoint;


/**
 * @author huangmy
 * @date   2008-1-11
 */
public class EndpointImpl extends AttributesImpl<String> implements Endpoint {
	private static final long serialVersionUID = 1L;
	private long id;
		
	public EndpointImpl(long id) {
		this.id = id;
	}
	
	public long getId() {		
		return this.id;
	}

	public String getURI() {		
		return createURI();
	}
	
	@Override
	public String toString() {		
		return getURI();
	}
	
	@Override
	public int hashCode() {		
		return getURI().hashCode();
	}
	
	@Override
	public boolean equals(Object obj) {		
		return getURI().equals(obj.toString());
	}
	
	private String createURI() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("uip://").append(id).append("?");

		for (Iterator<String> it = super.getAttributes().keySet().iterator(); it
				.hasNext();) {
			String name = it.next();
			
			buffer.append(name).append("=").append(super.getAttribute(name));
			if (it.hasNext()) {
				buffer.append("&");
			}			      
		}
		
		return buffer.toString();
	}
	
	public String getExpression() {
		StringBuffer buffer = new StringBuffer();
		buffer.append(id);
		
		if (super.getAttributes().size() > 0) {
			buffer.append("(");
		}
		
		for (Iterator<String> it = super.getAttributes().keySet()
				.iterator(); it.hasNext();) {
			String name = it.next();

			buffer.append(name).append("=").append(
					super.getAttribute(name));
			if (it.hasNext()) {
				buffer.append(",");
			}
		}
		
		if (super.getAttributes().size() > 0) {
			buffer.append(")");
		}
        			
		return buffer.toString();
	}
	
	public boolean atttibuesEqual(Endpoint endpoint) {
		if (getAttributes().size() != endpoint.getAttributes().size()) {			
			return false;
		}
		
		/*check properties*/
		for (Iterator<String> itp = endpoint.getAttributes().keySet().iterator(); itp.hasNext();) {
			String name = itp.next();
			String value = endpoint.getAttribute(name);
			String selfValue = getAttribute(name);
			
			if ((value == null && selfValue != null)
				|| (value != null && selfValue == null)) {				
				return false;
			}
			
			if (!value.equals(selfValue) && !value.equals("*") && !selfValue.equals("*")) {				
				return false;
			}
		}
		
		return true;
	}	
}
